var httpRequest = require('../../utils/httpRequest');
var utils = require('../../utils/util.js');
const app = getApp()
var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;
var drawFlag = false;
var arrx = [];
var arry = [];
var arrz = [];
var canvasw = 0;
var canvash = 0;

Page({
  data: {
    projectNo: '',
    achInfo: '',  // 项目基本信息
    userInfo: '',
    achList: [],
    hasUserInfo: false,
    isAach: true,
    isSign: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    qItems: [],
    rItems: [],
    aItems: [],
    pItems: [],
    fItems: [],
  },
  onLoad: function (options) {
    let that = this
    this.setData({
      projectNo: decodeURIComponent(options.scene)
    })
    
      
    //   // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          console.log(res.userInfo)
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          // this.popup.hidePopup();
        }
      })
    // }
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        canvasw = res.windowWidth;//设备宽度
        canvash = res.windowHeight
      }
    });
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getPhoneNumber: function(e) { //点击获取手机号码按钮
    var that = this;
    wx.checkSession({
      success: function() {
        console.log(e.detail.errMsg)
        console.log(e.detail.iv)
        console.log(e.detail.encryptedData)
        var ency = e.detail.encryptedData;
        var iv = e.detail.iv;
        var sessionk = that.data.sessionKey;
      }
    })
  },
  /**
   * 获取用户OpenId
   */
  getUserOpenId(code) {
    httpRequest.requestUrl({
      serverUrl: app.globalData.proUrl,
      url: "/webapi/wx/getOpenId" ,
      method: "get",
      params: {
        code: code
      },
    }).then(data => {
      if(data && data.code === 0){   

         resolve(data)
      }else{
        wx.showToast({
          title: '出错！', 
          icon: 'warn',   
          duration: 1500   // 提示窗停留时间，默认1500ms
      })
        reject(data)
      }
    })
  },
  /**
   * 初始化单选框
   */
  radioListInit(radio) {
    let items = [
      {value: 20,name: '非常满意'},
      {value: 18,name: '满意'},
      {value: 14,name: '基本满意'},
      {value: 10,name: '不满意'}
    ]
    switch (radio) {
      case 20:
        items[0].checked = true
        break
      case 18:
        items[1].checked = true
        break
      case 14:
        items[2].checked = true
        break
      case 10:
        items[3].checked = true
        break
      default:
        break
    }
    return items
  },
  radioChange: function(e) {
    let achItem = this.data.achInfo
    switch (e.currentTarget.id) {
      case 'qItems':
        achItem.gradeQuality = e.detail.value
        break
      case 'rItems':
        achItem.gradeRequire = e.detail.value
        break
      case 'aItems':
        achItem.gradeAttitude = e.detail.value
        break
      case 'pItems':
        achItem.gradeProgress = e.detail.value
        break
      case 'fItems':
        achItem.gradeProficiency = e.detail.value
        break
      case 'clientPhone':
        achItem.clientPhone = e.detail.value
        break
      case 'clientAdvice':
        achItem.clientAdvice = e.detail.value
        break
    }
    this.setData({
      achInfo: achItem
    })
    console.log(this.data.achInfo)
  },
  /**
   * 通过项目编号获取项目成果信息
   * @param {项目编号} projectNo 
   */
  getProjectInfo(projectNo) {
    let that = this
    return new Promise((resolve, reject) => {
      httpRequest.requestUrl({
        serverUrl: app.globalData.proUrl,
        url: "/webapi/ach/info/" ,
        method: "get",
        params:{ 'projectNo': projectNo }
      }).then(data => {
        if(data && data.code === 0){
          resolve(data)
        }else{
          wx.showLoading({
            title: '出错',
          });
          reject(data)
        }
      })
    })
  },
  dataFormSubmit () {
    if(drawFlag == false){
      wx.showToast({
        title: '请签名！', 
        icon: 'none',   
        duration: 2000   // 提示窗停留时间，默认1500ms
      })
      wx.pageScrollTo({
        duration: 1000,
        scrollTop: 10
      })
      return
    }
    let that = this
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      success(res) {
        console.log(res.tempFilePath)
        wx.getFileSystemManager().readFile({
            filePath: res.tempFilePath,  //图片路径
            encoding: 'base64', //编码格式
            success: res => { //成功的回调
              console.log('data:image/png;base64,' + res.data)
              let achVo = that.data.achInfo
              achVo.signature = res.data
              httpRequest.requestUrl({
                serverUrl: app.globalData.proUrl,
                url: "/webapi/ach/update" ,
                method: "post",
                params: {
                  projectNo: that.data.projectNo,
                  authachEntity: achVo
                },
              }).then(data => {
                if(data && data.code === 0){   
                  // that.getProjectInfo(that.data.projectNo)
                  wx.showToast({
                    title: '提交成功！', 
                    icon: 'success',   
                    duration: 1500   // 提示窗停留时间，默认1500ms
                  })
                   resolve(data)
                }else{
                  wx.showToast({
                    title: '提交出错！', 
                    icon: 'warn',   
                    duration: 1500   // 提示窗停留时间，默认1500ms
                })
                  reject(data)
                }
              })
            }
          })
      }
    })
  },
  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },
     //取消事件
     _error() {
      utils.TipModel('错误','拒绝授权，将无法获取签字权！', 0);
    },
    //确认事件
    _success() {
      if(app.globalData.userInfo) {
        this.setData({
          userInfo: app.globalData.userInfo
        })
        this.popup.hidePopup();
        wx.showToast({
          title: '授权成功！',
          icon: 'success',
          duration: 2000//持续的时间
        })
      }
    },
  //开始
  canvasStart: function (event) {
    drawFlag = true;
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
    //context.moveTo(event.changedTouches[0].x, event.changedTouches[0].y);

  },
//过程
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    };

    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };

    };
    context.clearRect(0, 0, canvasw, canvash);
    context.setFillStyle('#FFFFFF')
    context.setStrokeStyle("red")
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();

    context.draw(false);
  },
  canvasEnd: function (event) {
    isButtonDown = false;
  },
  cleardraw: function () {
    drawFlag = false;
    this.setData({
      isSign: false
    })
    //清除画布
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },
})